package com.itljm.cxrMarket.utils;

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Base64;

/**
 * @author ljm
 * @date 2024/12/11 15:12
 */
public class BASE64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String contentType;

    public BASE64DecodedMultipartFile(byte[] imgContent, String contentType) {
        this.imgContent = imgContent;
        this.contentType = contentType;
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + "_" + Math.random() + "." + getExtension();
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + "_" + (int)(Math.random() * 10000) + "." + getExtension();
    }

    private String getExtension() {
        if (contentType == null || contentType.isEmpty()) {
            return "dat"; // 默认扩展名
        }
        return contentType.split("/")[1];
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(imgContent);
        }
    }

    public static MultipartFile base64ToMultipart(String base64) {
        if (base64 == null || base64.isEmpty()) {
            return null;
        }

        String[] baseStrs = base64.split(",", 2);
        if (baseStrs.length != 2) {
            throw new IllegalArgumentException("Invalid Base64 string");
        }

        String header = baseStrs[0];
        byte[] b = Base64.getDecoder().decode(baseStrs[1]);

        return new BASE64DecodedMultipartFile(b, header.split(";")[0].split(":")[1]);
    }
}
